package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdLoginVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmLoginVo;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    /**
     * 自媒体人登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmLoginDto dto) {
        //参数校验
        if (dto == null || StringUtils.isBlank(dto.getName())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询用户是否存在
        LambdaQueryWrapper<WmUser> queryWrapper = Wrappers.<WmUser>lambdaQuery();
        queryWrapper.eq(WmUser::getName, dto.getName())
                .eq(WmUser::getStatus, 9);
        WmUser one = getOne(queryWrapper);
        if (one == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "账号或者密码错误");
        }
        //校验用户密码
        String salt = one.getSalt();
        String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        String dbpwd = one.getPassword();
        if (!pwd.equals(dbpwd)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "账号或者密码错误");
        }
        //生成token
        String token = AppJwtUtil.getToken(one.getId().longValue());
        //封装返回数据
        WmLoginVo wmLoginVo = new WmLoginVo();
        BeanUtils.copyProperties(one, wmLoginVo);

        Map map = new HashMap();
        map.put("token", token);
        map.put("user", wmLoginVo);
        return ResponseResult.okResult(map);

    }
}
